package cn.ljw.use;

import cn.ljw.mybatis.Resources;
import cn.ljw.mybatis.SqlSession;
import cn.ljw.mybatis.SqlSessionFactory;
import cn.ljw.mybatis.SqlSessionFactoryBuilder;
import cn.ljw.use.entity.User;
import com.alibaba.fastjson.JSON;

import java.io.Reader;
import java.util.List;

/**
 * @author 一朝风月
 * @date 2024/9/21 23:19
 * @Code 面向注解面向卿，终无解释再无你
 * @description
 */
public class MybatisTest {
    public void testQueryUserById() {
        String resource = "mybatis-config-datasource.xml";
        Reader reader;
        try {
            reader = Resources.getResourceAsReader(resource);
            SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);

            SqlSession session = sqlMapper.openSession();
            try {
                User user = session.selectOne("cn.ljw.use.mapper.UserMapper.queryUserById", 1);
                System.out.println(JSON.toJSONString(user));
            } finally {
                session.close();
                reader.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void testQueryUserList() {
        String resource = "mybatis-config-datasource.xml";
        Reader reader;
        try {
            reader = Resources.getResourceAsReader(resource);
            SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);

            SqlSession session = sqlMapper.openSession();
            try {
                User req = new User();
                req.setAge(18);
                List<User> userList = session.selectList("cn.ljw.use.mapper.UserMapper.queryUserList", req);
                System.out.println(JSON.toJSONString(userList));
            } finally {
                session.close();
                reader.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MybatisTest mybatisTest = new MybatisTest();
        mybatisTest.testQueryUserById();
        mybatisTest.testQueryUserList();
    }
}
